package com.ridanlabs.professorwebsite.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.paypal.adaptive.api.responses.PayResponse;
import com.paypal.adaptive.api.responses.PaymentDetailsResponse;
import com.paypal.adaptive.core.APICredential;

@Controller
@RequestMapping(value = "/paypal/*")
public class PayPalController {
	private static final Logger LOG = LoggerFactory
			.getLogger(CourseController.class.getName());

	// Credential info
	private final static String PP_API_USERNAME = "seller_1316378373_biz_api1.gmail.com";
	private final static String PP_API_PASSWORD = "1316378408";
	private final static String PP_API_SIGNATURE = "ABU7HSU87NC3YpXpbXpMQWeuIErQAdsPuFquj0ilhBkYFOI7zlYZevfr";
	private final static String PP_APP_ID = "APP-80W284485P519543T";
	private final static String PP_ACCOUNT_EMAIL = "seller_1316378373_biz@gmail.com";

	private static APICredential credentialObj;
	private static String payKey;

	static {
		credentialObj = new APICredential();
		credentialObj.setAPIUsername(PP_API_USERNAME);
		credentialObj.setAPIPassword(PP_API_PASSWORD);
		credentialObj.setSignature(PP_API_SIGNATURE);
		credentialObj.setAppId(PP_APP_ID);
		credentialObj.setAccountEmail(PP_ACCOUNT_EMAIL);

		LOG.info("API Credential created successfully");
	}

	@RequestMapping(value = "index")
	public String showServices() {
		return "paypal/index";
	}
	
	@RequestMapping(value = "simplepay", method = RequestMethod.GET)
	public String getSimplePay(HttpServletRequest req, HttpServletResponse resp) 
			throws IOException {
		return "paypal/simplepay";
	}

	@RequestMapping(value = "simplepay", method = RequestMethod.POST)
	public String doSimplePay(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			PayResponse payResp = PayPalRequests.processSimplePayRequest(req,
					resp, credentialObj);
			req.setAttribute("payResponse", payResp);
			return "paypal/simplepay";
			
		} catch (IOException e) {
			LOG.error("Redirecting to PayPal Authorization Failed.");
			return "paypal/index";
		}
	}

	@RequestMapping(value = "paydetails", method = RequestMethod.POST)
	public String doPayDetails(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		if (payKey != null) {
			PaymentDetailsResponse payDetailsResp = PayPalRequests
					.processPaymentDetails(resp, payKey, null, null,
							credentialObj);
			// do something with the payDetailsResp object
			return "paypal/index";
		} else {
			LOG.error("PayKey hasn't be acquired");
			return "paypal/index";
		}

	}

}
